import package_util as pu
import socket

from bound_check import *
from extract_background import extract_background
from bound_check import predict_one_request
from keras.preprocessing import image
from multiprocessing import Process
import multiprocessing as mul
import argparse


from yolo_hat import YOLO_HAT
from yolo_tempt import YOLO_TEMPT
from yolo_bike import YOLO_BIKE
from yolo_face import YOLO_FACE
from yolo_bin import YOLO_BIN


from PIL import Image
from PIL import ImageFile
from image_util import *
ImageFile.LOAD_TRUNCATED_IMAGES = True
from crop_image import crop_image,get_points,get_region_num,points_filter
import os
from keras.models import load_model
import os
import tensorflow as tf
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
from keras.backend.tensorflow_backend import set_session
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.9
set_session(tf.Session(config=config))
SERVER_PORT=7888
FLAGS = None
OPERATION_DIR="./yjjy_tempt"
STORAGE_DIR="yjjy_tempt/"





def handle_client(client_socket,pipe):

    """

    处理客户端请求

    """
    while True:
        request_data=pu.get_one_package(client_socket)
        print("request_data:",request_data)
        image_path = pu.get_package_json_value_by_key(request_data, "imagePath")
        ipc_id = pu.get_package_json_value_by_key(request_data, "ipcId")
        message_id=pu.get_package_json_value_by_key(request_data, "messageId")

        process_list = pu.get_package_json_value_by_key(request_data, "model")
        request_dic={}
        request_dic["image_path"]=image_path
        request_dic["ipc_id"]=ipc_id
        request_dic["message_id"]=message_id

        yjjy_params={}
        #设置放缩的图片分辨率
        image_size=[1920,1080]
        crop_image_size=[]
        crop_image_cord=[]
        server_result_dic={}

        IF_SEND_OBJ_DETECT_PACKAGE=False
        IF_SEND_YJJY_DETECT_PACKAGE=False

        # 循环处里一个请求包的不同请求


        for box_dic in process_list:
            model_num=box_dic["modelId"]
            print("model_id",model_num)
            if model_num in [104,110,101,113]:

                print("box_dic;",box_dic)

                IF_SEND_OBJ_DETECT_PACKAGE=True
                #scene_id=box_dic["sceneId"]
                scene_id=model_num
                #print("croping image>>>>>>")
                #print(box_dic)
                #print("1")
                #>>>
                crop_image_size.append(int((box_dic["xLength"]/1000*image_size[0])))
                crop_image_size.append(int(box_dic["yLength"]/1000*image_size[0]))
                crop_image_cord.append(int(box_dic["leftX"]/1000*image_size[0]))
                crop_image_cord.append(int(box_dic["leftY"]/1000*image_size[1]))
                #image_size=crop_img_percentage(get_percentage_list(box_dic),image_path)
                #print("2")
                #>>>
                crop_img_percentage(get_percentage_list(box_dic), image_path)
                #print("3")
                #同时发送场景编号>>>>>>>>>>......>>>>>>
                pipe.send("tempt_img.jpg"+str(model_num))
                print("tempt_img.jpg"+str(model_num))
                #print("4")
                result=pipe.recv()
                #完善处理结果的逻辑，把result中crop图片的xywh转换为整体图片的xywh
                print("result",result)
                #>>>
                result_=pu.trans_crop_box_params(image_size, crop_image_cord, result)
                print("result_",result_)
                server_result_dic[scene_id] = result_
                #print(result_)



                #print(server_result_dic)

            if model_num == 106:
                #print(box_dic)
                IF_SEND_YJJY_DETECT_PACKAGE=True
                print("processing yuejie>>>")
                #delete_trash()
                name_list=box_dic["nameList"]
                absolute_path=box_dic["parentPath"]
                image_path_list = []
                for path in name_list:
                    image_path_list.append(os.path.join(absolute_path,path))

                points=points_filter(get_points(box_dic))

                region_num=get_region_num(points)

                print("region_num:",region_num)

                time_ = time.strftime('%Y-%m-%d_%H:%M:%S')

                os.mkdir(os.path.join(STORAGE_DIR, time_))

                for i in range(region_num):
                    j = 0

                    for image_path in image_path_list:


                        crop_image(points[i], image_path, name_list[j], i,time_)
                        j += 1

                extract_background(region_num=region_num,time=time_)

                pipe.send(str(region_num)+time_ + str(model_num))

                result = pipe.recv()
                identify_list=eval(result)
                #server_result_package_yjjy = pu.generate_package_yjjy(request_dic,identify_list,model_num)
                yjjy_params["identify_list"]=identify_list
                yjjy_params["model_num"]=model_num
                # print(server_result_package)



        #send package>>>>
        if IF_SEND_OBJ_DETECT_PACKAGE:

            server_result_package = pu.generate_package(request_dic, server_result_dic)
            print("return message>>>>")
            print(server_result_package)
            client_socket.send(server_result_package)

        if IF_SEND_YJJY_DETECT_PACKAGE:
            #request_dic,identify_list,model_id
            server_result_package_yjjy=pu.generate_package_yjjy(request_dic,yjjy_params["identify_list"],yjjy_params["model_num"])
            print("return message>>>>")
            print(server_result_package_yjjy)
            client_socket.send(server_result_package_yjjy)








def server(pipe):
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind(("", SERVER_PORT))
    server_socket.listen(128)

    while True:
        client_socket, client_address = server_socket.accept()
        #print(client_socket)
        #print("[%s]用户连接上了" % (client_address))
        print("用户连接上了>>>")
        handle_client_process = Process(target=handle_client, args=(client_socket,pipe,))
        handle_client_process.start()





#此处是检测检测图片的逻辑
def detect_img(pipe,yolo_0,yolo_1,yolo_2,yolo_3,yolo_4,bound_check):
    while True:
        #img = pipe.recv()
        msg = pipe.recv()
        # print(type(msg))
        model_num =int(msg[-3:])

        #检查图片有效性
        #CHK_COMPLETE = check_image_valid(img)

        #secene_id 解析场景编号，决定调用具体的模型
        # if secene_id==X：
        #     》>》>》

        #if CHK_COMPLETE:




        #print("type",type(model_num))
        #print(model_num)
        if model_num == 101:
            img = msg[:-3]
            #print("img:", img)
            try:
                image = Image.open(img)
            except:
                image = Image.open("error.jpg")
            #print("loaded")
            #print("image:", img)
            request = yolo_1.detect_image(image)

            #print("predicted>>")

            pipe.send(request)
        if model_num == 104:
            img = msg[:-3]
            #print("img:",img)
            try:
                image = Image.open(img)
            except:
                image = Image.open("error.jpg")
                print('Open Error! Try again!')
                # pipe.send(img+"不存在！")
            #print("loaded")
            #img = msg[:-3]
            #print("image:", img)
            request_face = yolo_2.detect_image_2(image)

            #print("predicted>>")

            #print(request_face)
            #print(request_face=="")


            if request_face=="":

                pipe.send("")

            else:

                request_hat = yolo_4.detect_image(image)

                request = request_hat + request_face

                pipe.send(request)


        if model_num == 110:
            img = msg[:-3]

            try:
                image = Image.open(img)
            except:
                image = Image.open("error.jpg")
                print('Open Error! Try again!')
                # pipe.send(img+"不存在！")


            print("image:", img)
            request = yolo_3.detect_image_3(image)
            pipe.send(request)
        if model_num == 113:

            img = msg[:-3]
            try:
                image = Image.open(img)
            except:
                image = Image.open("error.jpg")
                print('Open Error! Try again!')
                # pipe.send(img+"不存在！")


            print("image:", img)
            request = yolo_0.detect_image(image)
            pipe.send(request)
        if model_num == 106:

            region_num = int(msg[:-22])
            time_crr = msg[-22:-3]
            request = predict_one_request(bound_check,region_num=region_num,time=time_crr)
            pipe.send(str(request))






if __name__ == '__main__':

    parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
    FLAGS = parser.parse_args()
    pipe = mul.Pipe()
    p1 = Process(target=server, args=(pipe[0],))
    p1.start()
    #handle_pipe(pipe[1])
    yolo_0=YOLO_TEMPT(**vars(FLAGS))
    yolo_1=YOLO_BIKE(**vars(FLAGS))
    yolo_2=YOLO_FACE(**vars(FLAGS))
    yolo_3=YOLO_BIN(**vars(FLAGS))
    yolo_4=YOLO_HAT(**vars(FLAGS))
    bound_check = get_bound_check_model()
    detect_img(pipe[1],yolo_0,yolo_1,yolo_2,yolo_3,yolo_4,bound_check)
    #detect_img(pipe[1], yolo_0, yolo_1, yolo_2, yolo_3)

    # detect_img(YOLO(**vars(FLAGS)),pipe[1])
    # detect_img(YOLO_2(**vars(FLAGS)),pipe[1])
    p1.join()
